import React, { Component, PropTypes } from 'react';
import {
  Text,
  View,
  Image,
  TouchableOpacity,
  DeviceEventEmitter,
  Platform,
  NativeAppEventEmitter,
  InteractionManager,
  Dimensions
} from 'react-native';

import styles from './imagePekerStyle';
import api from '../../services/api';
import Toast from 'react-native-sk-toast';
import LoadingTip from '../global/LoadingTip';
import ImagePicker from 'react-native-image-picker';
import RNFetchBlob from 'rn-fetch-blob'
import * as config from '../../constants/apiConfig';
import moment from 'moment';
import { Navigation } from '../global/navigation/index';
import SimpleDialog from '../global/SimpleDialog';
import Touch from '../global/Touch';

var windowWidth = Dimensions.get('window').width;
var windowHeight = Dimensions.get('window').height;

class ImagePeker extends Component {
    constructor(props) {
		super(props);

		this.state = {
			isUpload: false,
			// avatarSource: this.props.source,
            showLoading: false,
            fileUri:this.props.fileUri,
            orderId:this.props.orderId,
            fileName:this.props.fileName,
            openHandSignDialog:false

		};
        this.Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
		// this.props.navigator.setOnNavigatorEvent(this._onNavigatorEvent.bind(this));
	}
    componentWillMount() {
		// this._retrieveDetails();
	}

    componentWillUnmount(){
        // this._subcribOrder && this._subcribOrder.remove();
    }

    componentDidMount(){
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        // this._subcribOrder = Emitter.addListener('hand.sign.success', this._handWritingSignSuccess.bind(this));
    }
    componentWillUnmount(){
        // this._subcribOrder && this._subcribOrder.remove();
    }

    _goBack(){
        this.props.navigator.pop();
    }

    async _uploadImage(data){

        let {orderId} = this.props;
        let {fileUri} = this.state;
        let source = "data:image/jpeg;base64,"+data;
        let res = await api.post("/order/uploadimage",{id:orderId,image:source});
        if(res.data){
            
            this.setState({ isUpload: true, showLoading:false},() => {Toast.bottom("图片已上传");});
        }else{
            this.setState({showLoading:false})
        }


        
    }

    // _handWritingSignSuccess(){
    //     this.props.navigator.pop();
    //     console.log('test',"00000000000000000000000");
    // }

    async _uploadFinishImage(data){
        let {orderId} = this.props;
        let {fileUri} = this.state;
        let source = "data:image/jpeg;base64,"+data;
        let res = await api.post("/order/uploadfinishimage",{id:orderId,image:source});
        if(res.data){
            Toast.bottom("图片已上传");
            this.setState({ isUpload: true, showLoading:false});
        }else{
            this.setState({showLoading:false})
        }
        
    }

    _readFileToBase64(fileUri,orderPhone){
        this.setState({showLoading: true});
        let data = ''
        RNFetchBlob.fs.readStream(
            // file path
            fileUri,
            // encoding, should be one of `base64`, `utf8`, `ascii`
            'base64',
            // (optional) buffer size, default to 4096 (4095 for BASE64 encoded data)
            // when reading file in BASE64 encoding, buffer size must be multiples of 3.
            4095)
        .then((ifstream) => {
            ifstream.open()
            ifstream.onData((chunk) => {
              // when encoding is `ascii`, chunk will be an array contains numbers
              // otherwise it will be a string
              data += chunk
            })
            ifstream.onError((err) => {
                this.setState({showLoading: false})
            })
            ifstream.onEnd(() => {  
                if (orderPhone) {
                    this._uploadFinishImage(data);
                }else{
                    this._uploadImage(data);
                }
            })
        })
    }

    _resetCamera(){
        var options = {
            title: '拍照获取物品照片',
            cancelButtonTitle: "取消",
            quality: 0.8,
            maxHeight: parseInt(windowHeight*2),
            maxWidth: parseInt(windowWidth*2),
            storageOptions: {
                skipBackup: true,
                path: 'images'
            }
        };

        // this.props.navigator.pop();
        // 照片
        ImagePicker.launchCamera(options, (response)  => {
            // Same code as in above section!
            console.log('ImagePicker.launchCamera',response);
            if (response.error) {
            }else{
                if (response.didCancel) {
                   return;
                }
                this.setState({
                    isUpload:false,
                    fileUri:response.uri,
                    fileName:response.fileName,

                })
                InteractionManager.runAfterInteractions(() => {
                    console.log('ImagePicker.launchCamera--orderId',this.props.orderId);
                    console.log('ImagePicker.launchCamera--orderPhone',this.props.orderPhone);
                    console.log('ImagePicker.launchCamera--orderType',this.props.orderType);
                    console.log('ImagePicker.launchCamera--otherServiceType',this.props.otherServiceType);
                    console.log('ImagePicker.launchCamera--status',this.props.status);
                    console.log('ImagePicker.launchCamera--needPay',this.props.needPay);
                    console.log('ImagePicker.launchCamera--serviceCost',this.props.serviceCost);
                    console.log('ImagePicker.launchCamera--serviceCostDetail',this.props.serviceCostDetail);
                    this.props.navigator.push({
                        title: '确认物品照片',
            			screen: 'housekeeperapp.imagepicker',
                        backButtonTitle:'',
            			passProps: {
                            orderId: this.props.orderId,
                            orderPhone: this.props.orderPhone,
                            orderType: this.props.orderType,
            				// source: 'data:image/jpeg;base64,' + response.data
                            fileUri:response.uri,
                            otherServiceType:this.props.otherServiceType,
                            fileName:response.fileName,
                            status:this.props.status?this.props.status:-1,
                            needPay:this.props.needPay,
                            serviceCost:this.props.serviceCost,
                            serviceCostDetail:this.props.serviceCostDetail,
            			},
                        navigatorStyle:{
                            tabBarHidden: true,
                            navBarTextColor: 'white',
                        	navBarButtonColor: 'white',
                        	navBarBackgroundColor: '#EA5404',
                            statusBarColor: '#EA5404',
                            navBarTitleTextCentered: true,
                            topBarElevationShadowEnabled:false
                        },
                        navigatorButtons: {
                            leftButtons:[
                                {
                                    id: 'back',
                                    icon: require("../../../img/hk_back_icon.png")
                                }
                            ]
            			}
            		});

                });

            }
        });
    }

    async _actionGetobj(){
        let {orderId, from, orderType} = this.props;
        let res = await api.post("/order/updatestatus",{id:orderId,status:3,cancelReason:''});
        if(res.data){
            Toast.bottom(orderType=='other' || orderType == 'nursing' ? "服务已确认":"我已取货");
            this.props.navigator.pop();

            InteractionManager.runAfterInteractions(() => {

                if(from != 'detail'){
                    this.Emitter.emit('order.onload');
                }
            });

        }else{
            Toast.bottom("该笔订单已确认，请刷新后重试");
        }
    }
    // 购买的获取物品
    async _actionGetBuyobj(){
        let {orderId, from, orderPhone,otherServiceType,orderType} = this.props;
        let res = await api.post("/order/updatestatus",{id:orderId,status:4,cancelReason:''});
        if(res.data){
            // let ownerInfo = await api.post('/housekeeper/ownerinfobyphone',{phone: orderPhone});
            // if(ownerInfo.data){
            //     let send_text = "";
            //     let orderTrack = await api.post('/order/tracksdetail',{id: orderId});

            //     if(orderTrack.data){

            //         let { session } = this.props;
            //         let web_base_url = "";
            //         if (session && session.user && session.user.product && session.user.product.baseUrl) {
            //             web_base_url = session.user.product.baseUrl;
            //         }else{
            //             web_base_url = config.WEB_BASE_URL;
            //         }

            //         if (orderType=='other' && otherServiceType == 'activity') {
            //             send_text = "您的订单已完成。<a href='" + web_base_url + "/weichart/order?order_id="+orderId+"&type=ORDER_REWARD'>评价服务</a>";
            //         }else if (orderType == 'nursing') {
            //             let delayTime = ((moment(orderTrack.data.order_endsend_time) - moment(orderTrack.data.order_hkget_time))/60000).toFixed(0);
            //             send_text = "您的订单已完成，耗时"+delayTime+"分钟。<a href='" + web_base_url + "/weichart/order?order_id="+orderId+"&type=ORDER_REWARD'>评价服务</a>";
            //         }else{
            //             let delayTime = ((moment(orderTrack.data.order_endsend_time) - moment(orderTrack.data.order_hkget_time))/60000).toFixed(0);
            //             send_text = "您的订单已完成，耗时"+delayTime+"分钟。<a href='" + web_base_url + "/weichart/order?order_id="+orderId+"&type=ORDER_REWARD'>评价服务</a>";
            //         }
                    
                    

            //         let json = JSON.stringify({
            //                         "touser":ownerInfo.data.wxOpenId,
            //                         "msgtype":"text",
            //                         "text":
            //                         {
            //                              "content":send_text,
            //                         }
            //                     });

            //         let send_res = await api.post('/wx/customsend',{json});
            //     }

            // }

            Toast.bottom("我已完成");
            this.props.navigator.pop();

            InteractionManager.runAfterInteractions(() => {
                
                if(from != 'detail'){
                    this.Emitter.emit('order.onload');
                }
            });

        }else{
            Toast.bottom("该笔订单已完成，请刷新后重试");
        }
    }


    async _postPictureData(){
        this.setState({
            showLoading:true,
        })
        let {fileUri,fileName} = this.state;

        let file = {uri:fileUri,name:fileName,type:'image/jpeg'}
        let result = await api.upload('/file/upload',file,'ORDER')
        if (result.cd == 0) {
            let images = []
            images.push(result.data.id)
            this.setState({
                isUpload:true,
                showLoading:false,
                images:images,
            })
        }else{
            this.setState({
                showLoading:false,
            })
            Toast.bottom("上传失败:"+result.msg);
        }
    }

    // async _completeUpload(){
    //     let {orderType,orderId,needPay} = this.props;
    //     let{images} = this.state;
    //     console.log('test',orderType);
    //     if (needPay) {
    //         this.setState({
    //             showLoading:true,
    //         })
    //         let result = await api.post('/order/uploadImage',{id:orderId,type:'ORDER_FINISH_IMAGE',images:images})
    //         if (result.cd == 0) {
    //             this._sentServiceCost(orderType);
    //         }else{
    //             this.setState({
    //                 showLoading:false,
    //             })
    //             Toast.bottom("创建失败:"+result.msg);
    //         }
    //     }else{
    //         if (orderType == "nursing") {
    //             this.setState({openHandSignDialog:true,showLoading:false})

    //         }else{
    //             this._updateStatus(orderId);
    //         }
    //     }
    // }

    async _completeUpload(){
        let {orderType} = this.props;
        console.log('test',orderType);
        this.setState({
            showLoading:true,
        })
        let{images} = this.state;
        let {orderId,needPay} = this.props;
        let result = await api.post('/order/uploadImage',{id:orderId,type:'ORDER_FINISH_IMAGE',images:images})
        if (result.cd == 0) {

            if (needPay) {//需要支付
                this._sentServiceCost(orderType);
            }else{
                if (orderType == "nursing") {
                    this.setState({openHandSignDialog:true,showLoading:false})

                }else{
                    this._updateStatus(orderId);
                }
            }
        }else{
            this.setState({
                showLoading:false,
            })
            Toast.bottom("创建失败:"+result.msg);
        }
    }

    _renderHandSignDialog(){
        return (
            <SimpleDialog
                offset={0}
                showModal={this.state.openHandSignDialog}
                closeOnTouchOutside={false}
                dialogContainerStyle={{marginLeft:40,marginRight:40,marginTop: 240}}
                parent={this}
                modalDidOpen={() => console.log('modal did open')}
                modalDidClose={() => console.log('modal did close')}>
                    <View style={styles.dialogContainer}>
                        <View style={{alignItems:'center',marginTop:40}}>
                            <Text style={styles.dialogBodyText}>
                                请用户进行签名
                            </Text>
                        </View>
                        <View style={[styles.submitBtnContainer,{marginTop:40}]}>
                            <Touch onPress={() =>{this.setState({openHandSignDialog: false})}} style={styles.submitCancelBtn}>
                                <Text style={styles.submitBtnText}>暂不签名</Text>
                            </Touch>
                            <Touch onPress={this._openHandSignActivity.bind(this)} style={styles.submitOkBtn}>
                                <Text style={[styles.submitBtnText,{color:'#EA5404'}]}>立即签名</Text>
                            </Touch>
                        </View>
                    </View>
              </SimpleDialog>
        )
    }

    _openHandSignActivity(){
        let {orderId} = this.props;
        let {images} = this.state;
        // Navigation.startHandSignActivity({order_id:orderId,type:'ORDER_FINISH_IMAGE',images});
        Navigation.startHandSignActivity({order_id:orderId});
        this.props.navigator.pop();
    }

    async _sentServiceCost(orderType){
        let {orderId,serviceCost,serviceCostDetail} = this.props;
        // let send_res = await api.post("/wx/customsend");
        let res = await api.post("/order/setServiceCost",{id:orderId,serviceCost,serviceCostDetail});

        this.setState({ showLoading: false });
        if (res.cd == 1){
            Toast.bottom(res.msg);
            return;
        }

        if(res.data){
            // if (orderType == "nursing") {
            //     this.setState({openHandSignDialog:true})
            // }else{
                this.props.navigator.pop();
                let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
                    Emitter.emit("pop");
                    Emitter.emit("order.onload")
            // }
            
        }else{
            Toast.bottom("该笔订单已设置服务金额，请刷新后重试");
        }
    }

    async _updateStatus(id){
        let {session,orderPhone,orderType,otherServiceType} = this.props;
        let res = await api.post("/order/updatestatus", {
            id: id,
            status: 4,
            cancelReason:''
        });
        console.log('_updateStatus=====------/order/updatestatus',res);
        if(res.cd == 1){

            this.setState({
                showLoading:false,
            })
            Toast.bottom(res.msg);
            return;
        }
        this.setState({
            showLoading:false,
        })
        Toast.bottom("该笔订单已完成");
        this.props.navigator.pop();
        let Emitter = Platform.OS === 'android' ? DeviceEventEmitter : NativeAppEventEmitter;
        Emitter.emit("pop");
            
        // if (res.data) {
        //     let ownerInfo = await api.post("/housekeeper/ownerinfobyphone", {
        //         phone: orderPhone
        //     });

            // if (ownerInfo.data) {
            //     let send_text = "";
            //     let orderTrack = await api.post("/order/tracksdetail", {
            //         id: id
            //     });
            //     if (orderTrack.data) {
            //         let delayTime = (
            //             (moment(orderTrack.data.order_endsend_time) -
            //                 moment(orderTrack.data.order_hkget_time)) /
            //             60000
            //         ).toFixed(0);

            //         // let { session } = this.props;
            //         let web_base_url = "";
            //         if (session && session.user && session.user.product && session.user.product.baseUrl) {
            //             web_base_url = session.user.product.baseUrl;
            //         }else{
            //             web_base_url = config.WEB_BASE_URL;
            //         }


            //         if (orderType == 'other' && otherServiceType == 'activity') {
            //             send_text =
            //                 "您的订单已完成。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 id +
            //                 "&type=ORDER_REWARD&othertype="+otherServiceType+"'>评价服务</a>";
            //         }else if (orderType == 'nursing') {
            //             send_text =
            //                 "您的订单已完成。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 id +
            //                 "&type=ORDER_REWARD&othertype=nursing'>评价服务</a>";
            //         }else{
            //             send_text =
            //                 "您的订单已完成，耗时" +
            //                 delayTime +
            //                 "分钟。<a href='" +
            //                 web_base_url +
            //                 "/weichart/order?order_id=" +
            //                 id +
            //                 "&type=ORDER_REWARD&othertype="+otherServiceType+"'>评价服务</a>";
            //         }
                    
            //         let json = JSON.stringify({
            //             touser: ownerInfo.data.wxOpenId,
            //             msgtype: "text",
            //             text: {
            //                 content: send_text
            //             }
            //             // "customservice":
            //             // {
            //             //     "kf_account": session && session.user.kf_account
            //             // }
            //         });

            //         let send_res = await api.post("/wx/customsend", { json });
            //     }
            // }
    }

    _hasUploading(){
        let {orderPhone,orderType,status} = this.props;
        let {fileUri} = this.state;
        return (
            <View style={styles.containerOverlayout}>
                <TouchableOpacity style={styles.leftImage} onPress={this._goBack.bind(this)}>
                    <Image source={require('../../../img/hk_imagepeker_goback_icon.png')} />
                </TouchableOpacity>
                <TouchableOpacity style={styles.rightImage} onPress={orderType == 'nursing' && status == 3 ? this._postPictureData.bind(this) : this._readFileToBase64.bind(this,fileUri,orderPhone)}>
                    <Image source={require('../../../img/hk_imagepeker_ok_icon.png')}/>
                </TouchableOpacity>
            </View>
        )
    }

    _hasUploaded(){
        let {orderPhone, orderType,status} = this.props;
        return (
            <View style={styles.containerOverlayout}>
                <Text style={styles.topText}>图片已上传</Text>
                <View style={styles.bottomBtnContent}>
                    <TouchableOpacity style={styles.leftBtn} onPress={this._resetCamera.bind(this)}>
                        <Text style={styles.btnText}>重新拍摄</Text>
                    </TouchableOpacity>
                    <TouchableOpacity style={styles.rightBtn} onPress={orderType == 'nursing' && status == 3 ? this._completeUpload.bind(this) : orderPhone?this._actionGetBuyobj.bind(this):this._actionGetobj.bind(this)}>
                        <Text style={[styles.btnText,{color: '#fff'}]}>{orderPhone?'我已完成':(orderType=='other' || orderType=='nursing'?'确认服务':'确认取货')}</Text>
                    </TouchableOpacity>
                </View>
            </View>
        )
    }

    render() {
        return (
            <View style={styles.container}>
                <Image source={{uri: this.state.fileUri}} resizeMode="contain" style={styles.uploadAvatar}/>

                {this.state.isUpload?this._hasUploaded():this._hasUploading()}
                {this._renderHandSignDialog()}
                <LoadingTip show={this.state.showLoading}/>
                
            </View>
        );
    }
}

var connectHelper = require('../../services/connectHelper');
ImagePeker = connectHelper(state => state)(ImagePeker);

module.exports = ImagePeker;
